<template>
  <div>
    <el-breadcrumb separator-class="iconfont icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <div style="margin-top: 5px">
        <el-row type="flex" justify="space-between">
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
              maxlength="250px"
            >
              <el-button
                slot="append"
                @click="getUserList"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </el-col>

          <el-button type="primary" @click="addDialogVisible = true"
            >新增用户</el-button
          >
        </el-row>
      </div>
      <template>
        <el-table :data="userList" stripe style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="120">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="180">
          </el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <!-- 作用域插槽 -->
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!-- 作用域插槽 slot-scope="scope" -->
            <template width="210" slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-tooltip
                effect="dark"
                content="编辑"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  size="mini"
                  @click="getEditForm(scope.row)"
                  icon="el-icon-edit"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  size="mini"
                  icon="el-icon-setting"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                effect="dark"
                content="删除"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteUser(scope.row)"
                  icon="el-icon-delete"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <div class="block pageNum">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </template>
    </el-card>


  <!-- ==================================弹窗区域=========================================== -->
    <!-- 新增用户的弹窗 -->
    <el-dialog
      title="新增用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 主题内容区域 表单-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="addForm.telephone"></el-input>
        </el-form-item>
        
      </el-form>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑用户的弹窗 -->
    <el-dialog
      title="编辑信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 主题内容区域 表单-->
      <el-form
        :model="editForm"
        
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="editForm.telephone"></el-input>
        </el-form-item>
        
      </el-form>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证[自定义方式]--邮箱
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        //合法
        return cb();
      } else {
        //非法
        cb(new Error("请输入合法的邮箱"));
      }
    };
    // 验证--手机号
    var checkTele = (rule, value, cb) => {
      //验证手机的正则表达式
      const regTele =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regTele.test(value)) {
        return cb();
      } else {
        cb(new Error("请输入合法的手机号"));
      }
    };

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",

        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      // 用户列表
      userList: [],
      // 总数据条数
      total: 0,
      // 控制添加用户窗口的显示与隐藏
      addDialogVisible: false,
      // 控制编辑信息窗口1显示与隐藏
      editDialogVisible: false,


      // 表单-----添加用户
      addForm: {
        username: "",
        telephone: "",
        password: "",
        email: ""
      },
      editForm: {
        id: "",
        username: "",
        telephone: "",
        email: ""
      },
      // 验证-----添加用户
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2~10个字符", trigger: "blur" },
        ],
        telephone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkTele, trigger: "blur" },


          // { pattern: '/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/',
          // message: "电话号码格式错误", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur"}
        ],
        password: [
          { required: true, message: "请输入用户的角色", trigger: "blur" },
          { min: 1, max: 16, message: "请输入1~16个字符", trigger: "blur"}
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败！");
      this.userList = res.data.users;
      this.total = res.data.total;
      //console.log(res);
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听 用户权限状态 改变的事件【怎么有时候没反应??】
    async userStateChange(userInfo) {
      // console.log(userInfo.mg_state);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userInfo.mg_state;
        return this.$message.error(res.meta.msg);
      }

      return this.$message.success(res.meta.msg);
    },
    // 监听 添加用户对话框关闭的事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      
    },
    // 点击确定按钮添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户的网络请求
        const {data: res} = await this.$http.post('users', 
        {
          username: this.addForm.username,
          password: this.addForm.password,
          mobile: this.addForm.telephone,
          email: this.addForm.email
        },
        )
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败！')
          console.log(res)
        } else {
          this.$message.success('添加用户成功！')
          this.addDialogVisible = false
          this.getUserList()
        }

      })
    },
    // 获取待编辑的用户信息
    getEditForm(userInfo) {
      console.log(userInfo)
      this.editForm.id = userInfo.id
      this.editForm.username = userInfo.username
      this.editForm.telephone = userInfo.mobile
      this.editForm.email = userInfo.email
      this.editDialogVisible = true
    },
    // 提交编辑用户信息
    async editUser() {
      const {data: res} = await this.$http.put("users/"+this.editForm.id, 
      {
        email: this.editForm.email,
        mobile: this.editForm.telephone
      },
      )
      if(res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      else {
        this.$message.success(res.meta.msg)
      }
      
      //关闭窗口
      this.editDialogVisible = false
      //刷新界面
      this.getUserList()
    },

    // 删除用户
    deleteUser(userInfo) {
        this.$confirm("此操作将永久删除用户【"+userInfo.username+"】, 是否继续?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res} = await this.$http.delete('users/'+userInfo.id)
          if(res.meta.status != 200) {
            this.$message.error('删除失败')
          } else {
            this.$message.success('删除成功')
          }
          this.getUserList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }

  },
};
</script>
<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  margin-top: 15px;
  width: 100%;
  box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.pageNum {
  margin-top: 20px;
}
</style>